import logging
import datetime

from google.appengine.api import mail

import msg

def GetDateStr(d):
  delta = d.utcnow() - d
  if delta.days > 10:
    return d.strftime("%Y-%m-%d")
  elif delta.days > 0:
    return "%s %s" % (delta.days, msg.Get("days ago"))
  elif delta.seconds > 3600:
    return "%s %s" % (delta.seconds/3600, msg.Get("hours ago"))
  elif delta.seconds > 60:
    return "%s %s" % (delta.seconds/60, msg.Get("minutes ago"))
  else:
    return "%s %s" % (delta.seconds, msg.Get("seconds ago"))


def Log(text):
  logging.error("%s: %s" % ('*'*4, text))

def GetInt(value):
  try: 
    result = int(value)
    return (True, result)
  except ValueError:
    return (False, 0)

def MaybePrependHttp(url):
  if url.startswith('http'):
    return url
  else:
    return "http://%s" % url


def SendMail(receivers, subject, body):
  sender_address = "dizhen@gmail.com"
  for receiver in receivers:
    mail.send_mail(sender_address, receiver, subject, body)

# send email to the subscribers of this request
def NotifyRequestUpdate(self, req):
  #TODO: generate a digest of this request
  subject = req.item_name
  body = req.key
  SendMail(req.notifiers, subject, body)
